﻿using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Content.Res;
using Android.OS;
using Android.Provider;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using NightPlayer.views;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace NightPlayer
{
    [Activity(Label = "@string/app_name", 
        Theme = "@style/AppTheme", 
        MainLauncher = true, 
        Exported = true, 
        LaunchMode = Android.Content.PM.LaunchMode.SingleTop, 
        ScreenOrientation = Android.Content.PM.ScreenOrientation.Unspecified,
        ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.ScreenLayout | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ColorMode,
        
        Name = "com.zyfdroid.nightplayer.LauncherActivity"
        )]
    [IntentFilter(
        new[] { Intent.ActionView }, // 必须包含 ActionView
        Categories = new[] {
            Intent.CategoryDefault, // 必须包含 CategoryDefault
            Intent.CategoryBrowsable // 必须包含 CategoryBrowsable，才能从浏览器中启动
        },
        DataScheme = "nightplayer" // 定义你的协议名称
    )]
    [MetaData("android.app.shortcuts", Resource = "@xml/shortcuts")]
    public class LauncherActivity : BaseActivity
    {


        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            if (isEink)
            {
                RequestedOrientation = ScreenOrientation.Portrait;
            }
            if(PlayerService.player != null)
            {
                StartActivity(new Intent(this,typeof(MainActivity)));
                Finish();
                return;
            }
            SetContentView(Resource.Layout.splash);
            if (!isEink) {
                Window.SetNavigationBarColor(Android.Graphics.Color.Black);
            }
           
            if (string.IsNullOrEmpty(PrefTreeUri) || !PrefInited)
            {
                ShowPrivacyDialog();
            }
            else {
                runBegin();
            }
        }

        

        private void ProcessIncomingIntent(Intent intent,out bool autoplay)
        {
            
            // 1. 将 out 参数初始化为默认值 false
            autoplay = false;
            var data = intent?.Data;
            if (data != null)
            {
                // data 是一个 Android.Net.Uri 对象
                string scheme = data.Scheme; // "nightplayer"
                string host = data.Host;     // 如果 URL 是 nightplayer://playlist1?autoplay=true，这里会是 "playlist1"
                if(scheme.ToLower() == "nightplayer")
                {
                    string autoplayValue = data.GetQueryParameter("autoplay");

                    // 3. 判断参数值
                    //    "true".Equals(value, StringComparison.OrdinalIgnoreCase) 是进行不区分大小写比较的最佳实践
                    if ("true".Equals(autoplayValue, StringComparison.OrdinalIgnoreCase))
                    {
                        autoplay = true;
                    }
                    // 获取不带前导斜杠的路径内容
                    string extractedData = host.Trim('/');
                    if (string.IsNullOrEmpty(extractedData))
                    {
                        extractedData = "default";
                    }
                    PlayerService.prefslot = extractedData;
                }
                
            }
            
        }


        public const string AUDIODIR = "exaudio00004";
        ISharedPreferences SharedPreferences => GetSharedPreferences("main3", FileCreationMode.Private)!;

        public string? PrefMusicRoot
        {
            get => SharedPreferences.GetString("musicroot", "/mnt/saf");
            set => SharedPreferences.Edit()!.PutString("musicroot", value)!.Apply();
        }

        public bool PrefInited
        {
            get => SharedPreferences.GetBoolean("inited", false);
            set => SharedPreferences.Edit()!.PutBoolean("inited", value)!.Apply();
        }


        public string? PrefTreeUri
        {
            get => SharedPreferences.GetString("treeuri", "");
            set => SharedPreferences.Edit()!.PutString("treeuri", value)!.Apply();
        }

        void ensureFileExists() {
            Java.IO.File f = new Java.IO.File(FilesDir, AUDIODIR);
            if (!f.Exists()) { f.Mkdirs(); }
            Assets!.List("")!.Where(a => a.EndsWith(".ogg")).ToList().ForEach(f2 =>
            {
                Android.Util.Log.Warn("extracting assets", f2);
                String destpath = Path.Combine(f.AbsolutePath, f2);
                if (!File.Exists(destpath))
                {
                    using (FileStream fs = File.Open(destpath + ".tmp", FileMode.Create))
                    {
                        using (Stream ins = Assets.Open(f2))
                        {
                            ins.CopyTo(fs);
                        }
                    }
                    File.Move(destpath + ".tmp", destpath);
                }
            });

            Dictionary<string,string> namemapping = new Dictionary<string, string>
            {
                { "noise_white.ogg", "01 - 白噪音.nof" },
                { "noise_pink.ogg", "02 - 粉噪音.nof" },
                { "noise_brown.ogg", "03 - 褐噪音.nof" },
                { "rain.ogg", "04 - 雨.nof" },
                { "riverside.ogg", "05 - 河边.nof" },
                { "summer.ogg", "06 - 夏夜.nof" },
                { "wave.ogg", "07 - 海浪.nof" }
            };

            foreach (KeyValuePair<string, string> entry in namemapping) {
                if (!File.Exists(Path.Combine(f.AbsolutePath, entry.Value)))
                {
                    File.Copy(Path.Combine(f.AbsolutePath, entry.Key), Path.Combine(f.AbsolutePath, entry.Value));
                }
            }
            
        }

        void warn(String text) {
            new AlertDialog.Builder(this).SetCancelable(false)!.SetMessage(text)!.SetPositiveButton("退出", new EventHandler<DialogClickEventArgs>((sender, e) => Finish()))!
                .Create()!.Show();
         
        }
        void ShowPrivacyDialog()
        {
            string privacyMsg = @"隐私协议：
- 本软件不包含服务端，也没有内置第三方统计服务等。不会上传任何信息。
权限说明：
- 手动选择一个文件夹并获取该文件夹的读写权限：用于读取音乐和保存播放列表
- 启动前台服务：用于创建音乐播放服务（
- 保持CPU运行（保持唤醒）：使锁屏后音乐不会停止播放
- 网络权限：通过局域网控制音乐播放，可以用于智能家居，具体请参阅源代码";
            AlertDialog? dialog = null;
            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
            builder.SetTitle("使用说明：");
            builder.SetMessage(privacyMsg);
            builder.SetPositiveButton("选择音乐目录", (sender, e) =>
            {
                SelectDir();
            });
            builder.SetNeutralButton("以后再说", (sender, e) =>
            {
                Finish();
                dialog!.Dismiss();
            });

            builder.SetNegativeButton("不同意", (sender, e) =>
            {
                Android.Net.Uri uri = Android.Net.Uri.FromParts("package", Application!.PackageName, null)!;
                Intent intent = new Intent(Intent.ActionDelete,uri);
                StartActivity(intent);
                Finish();
                dialog!.Dismiss();
            });
            builder.SetCancelable(false);
            dialog = builder.Show()!;
        }
        private const int RequestCodeForTree = 42; 
        void SelectDir()
        {
            StartActivityForResult(new Intent(Intent.ActionOpenDocumentTree), RequestCodeForTree);
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent? data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            if (requestCode == RequestCodeForTree) { 
                if(resultCode == Result.Canceled)
                {
                    warn("未选择音乐文件夹");
                    return;
                }
                Android.Net.Uri? uri = data?.Data;
                if (uri == null)
                {
                    warn("未选择音乐文件夹");
                    return;
                }
                int FLAG_GRANT_READ_URI_PERMISSION = 0x00000001;
                int FLAG_GRANT_WRITE_URI_PERMISSION = 0x00000002;

                int takeFlags =  (FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
                ContentResolver!.TakePersistableUriPermission(uri, (ActivityFlags)takeFlags);
                PrefTreeUri = uri.ToString();
                PrefInited = true;
                runBegin();
            }
        }

        void runBegin() {
            if (!PrefInited)
            {
                return;
            }
            var fsImpl = new TheFxxkingSAFFileIOImpl(ApplicationContext!, PrefTreeUri!);
            AndroidIO.SetImpl(fsImpl);
            PlayerService.prefslot = "default";
            var slot = Intent?.GetStringExtra("slot");
            if (!string.IsNullOrEmpty(slot))
            {
                PlayerService.prefslot = slot.ToLower();
                
            }
            ProcessIncomingIntent(Intent,out bool autoplay);

            new Thread(delegate ()
            {
                ensureFileExists();
                Log.Info("MusicInit","BeginInit");
                if (PlayerService.playlist == null)
                {
                    Java.IO.File f = FilesDir!;
                    if (!f.Exists()) { f.Mkdirs(); }
                    f = new Java.IO.File(f, PlayerService.prefslot);
                    if (!f.Exists()) { f.Mkdirs(); }

                    
                    Console.WriteLine("Begin scan music dir");
                    PlayerService.playlist = new FantasticMusicPlayer.CurrentDirectorySongProvider(PrefMusicRoot!,new Java.IO.File(f,"point.conf").AbsolutePath);

                    Log.Info("MusicInit", "BeginInit3");
                    if (PlayerService.playlist.PlayLists == null ||  PlayerService.playlist.PlayLists.Count == 0)
                    {
                        PlayerService.playlist = null; 
                        PrefInited = false;
                        RunOnUiThread(() =>warn("在 内部存储/"+PrefMusicRoot+" 文件夹中没有找到音乐，请创建这个文件夹，并将音乐复制到这个文件夹"));
                        return;
                    }
                    

                    PlayerService.playlist.loadProgress();
                    RunOnUiThread(() => {
                        Intent serviceIntent = new Intent(this, typeof(PlayerService));
                        serviceIntent.PutExtra("autoplay", autoplay);
                        StartService(serviceIntent);  
                    });
                    while (PlayerService.player == null)
                    {
                        Thread.Sleep(200);
                    }
                }
                else
                {
                    Thread.Sleep(300);
                }



                RunOnUiThread(() => StartActivity(new Intent(this, typeof(MainActivity))));
                RunOnUiThread(() => Finish());
            }).Start();
        }
    }
}